<?php
/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace AppBundle\EventSubscriber;

use AppBundle\Entity\User;
use AppBundle\Entity\Company;
use AppBundle\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\EventDispatcher\GenericEvent;
use Doctrine\Common\Persistence\ObjectManager;
/**
 * Notifies post's author about new comments.
 *
 * @author Oleg Voronkovich <oleg-voronkovich@yandex.ru>
 */
class UserNotificationSubscriber implements EventSubscriberInterface
{
    private $_em;

    public function __construct(ObjectManager $em)
    {
        $this->_em = $em;
    }

    public static function getSubscribedEvents()
    {
        return [
            Events::USER_BEFORE_CREATE => 'onBeforeCreate',
        ];
    }

    public function onBeforeCreate(GenericEvent $event)
    {
        /** @var  $user User*/
        $user = $event->getSubject();
        if($user->getCompanyId() === null){
            $em = $this->_em;
            $company = new Company();
            $em->persist($company);
            $em->flush();
            $user->setPower(User::POWER_ADMIN);
            $user->setCompanyId($company->getId());
        }else {
            $user->setPower(User::POWER_USER);
        }
    }
}